package com.htx.zqs.blesmartmask.ui.fragment;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.htx.zqs.blesmartmask.BuildConfig;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.LocationData;
import com.htx.zqs.blesmartmask.eventbus.MessageEvent;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.ui.dialog.SelectDialog;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.CameraUtil;
import com.htx.zqs.blesmartmask.utils.LocationHelper;
import com.htx.zqs.blesmartmask.utils.LocationUtil;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;
import com.htx.zqs.blesmartmask.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.picker.SinglePicker;
import de.hdodenhof.circleimageview.CircleImageView;

import static android.app.Activity.RESULT_OK;


/**
 * Created by zhao on 2018/5/11.
 */

public class OrderFragment extends BaseFragment {
    private static final int REQUEST_CODE = 430;
    @InjectView(R.id.iv_fg_choose_picture)
    CircleImageView ivFgChoosePicture;
    @InjectView(R.id.tv_fg_choose_picture)
    TextView        tvFgChoosePicture;
    @InjectView(R.id.tv_fg_name)
    TextView        tvFgName;
    @InjectView(R.id.tv_fg_age)
    TextView        tvFgAge;
    @InjectView(R.id.tv_fg_sex)
    TextView        tvFgSex;
    @InjectView(R.id.tv_fg_phone)
    TextView        tvFgPhone;
    @InjectView(R.id.ll_fg_name)
    LinearLayout    mLlFgName;
    @InjectView(R.id.ll_fg_age)
    LinearLayout    mLlFgAge;
    @InjectView(R.id.ll_fg_sex)
    LinearLayout    mLlFgSex;
    @InjectView(R.id.ll_fg_phone)
    LinearLayout    mLlFgPhone;

    private String[]   sexs;
    private String[]   ages;
    private boolean    isCommitInfo;
    private String     orderName;
    private String     orderPhone;
    private String     orderAge;
    private String     orderSex;
    private CameraUtil cameraUtil;
    private File       tempFile;
    private Bitmap     bitmap;
    private HashMap map = new HashMap();
    private String   mUniquePsuedoID;
    private Location bestLocation;
    private String   city;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_order, container, false);
        ButterKnife.inject(this, view);
        initView();
        // 注册订阅者
        EventBus.getDefault().register(this);
        mUniquePsuedoID = LocationUtil.getUniquePsuedoID();
        return view;
    }

    private void getUserAddress() {
//        bestLocation = LocationUtil.getBestLocation(getContext());
//        List<Address> locationInfos = LocationUtil.getLocationInfo(bestLocation, getContext());
        LocationHelper.startLocation(new LocationHelper.OnLocationListener() {
            @Override
            public void onLocationComplete(LocationData locationData) {
                Log.e("=loca==", "===" + locationData);
                if (locationData.country.equals("中国")) {
                    city = locationData.getProvince() + locationData.getCity();
                } else {
                    LocationData locationData1 = LocationHelper.googleLocation(getContext(), locationData.getgLng(), locationData.getgLat());
                    city = locationData1.getProvince() + locationData1.getCity();
                }
//                map.clear();
//                map.put("",city);
//                mOkhttpUtils.postForm(Contants.ORDER_INFO_CODE, Contants.BASE_URL + "ug.link", map);
            }

            @Override
            public void onLocationFailed() {

            }
        });
//        if (locationInfos == null || locationInfos.size() == 0) {
//            city = "";
//        } else {
//            city = locationInfos.get(0).getAdminArea() + locationInfos.get(0).getLocality();
//        }
    }

    private void initView() {
        mUniquePsuedoID = LocationUtil.getUniquePsuedoID();
        cameraUtil = new CameraUtil();
        String localUri = (String) SPUtil.get(getContext(), "uri", "", "uri");
        if (!localUri.equals("")) {
            showPhoto(Uri.parse(localUri));
        } else {
            ivFgChoosePicture.setImageResource(R.drawable.circle_elves_ball);
        }
        isCommitInfo = (boolean) SPUtil.get(getContext(), "isCommitInfo", false, "isCommitInfo");
        if (isCommitInfo) {
            String json = (String) SPUtil.get(getContext(), "orderInfo", "", "orderInfo");
            try {
                JSONObject jsonObject = new JSONObject(json);
                orderName = (String) jsonObject.get("orderName");
                orderAge = (String) jsonObject.get("orderAge");
                orderSex = (String) jsonObject.get("orderSex");
                orderPhone = (String) jsonObject.get("orderPhone");
                tvFgName.setText(orderName);
                tvFgAge.setText(orderAge);
                tvFgSex.setText(Utils.getSexInternal(getContext(),orderSex));
                tvFgPhone.setText(orderPhone);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e("json", "initView: " + json);
        }
        ages = new String[100];
        for (int i = 0; i < 100; i++) {
            ages[i] = i + "";
        }
        sexs = new String[2];
        sexs[0] = getResources().getString(R.string.order_sex_man);
        sexs[1] = getResources().getString(R.string.order_sex_woman);
        if (BlEUtile.isNetworkConnected(getContext())) {
            getUserAddress();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Log.e("camera", "onActivityResult发生了什么: " + 111 + "" + intent);
        switch (requestCode) {
            case Contants.CAMERA_REQUEST_CODE:   //调用相机后返回
                Log.e("camera", "onActivityResult去哪里: " + 111);
                if (resultCode == RESULT_OK) {
                    CameraUtil.flushPciture(getContext(), tempFile.getAbsolutePath());

                    //用相机返回的照片去调用剪裁也需要对Uri进行处理
                    Log.e("camera", "onActivityResult去哪里: " + 222);
                    Uri uri = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        uri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".fileprovider", tempFile);

                        uri = Uri.fromFile(tempFile);
                        // cropPhoto(contentUri);
                        Log.e("camera", "onActivityResult哪里: " + uri);
                        //    Glide.with(this).load(contentUri).into(mHeader_iv);
                    } else {
                        Log.e("camera", "onActivityResult: 这" + Uri.fromFile(tempFile));
                        uri = Uri.fromFile(tempFile);

//                        mHeader_iv.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                        // cropPhoto(Uri.fromFile(tempFile));

                        //   Glide.with(this).load(Uri.fromFile(tempFile)).into(mHeader_iv);
                        //cropPhoto(Uri.fromFile(tempFile));
                    }
                    showPhoto(uri);
                }
                break;

            case REQUEST_CODE:
                if (intent != null) {
                    //获取选择器返回的数据
                    ArrayList<String> images = intent.getStringArrayListExtra(
                            ImageSelectorUtils.SELECT_RESULT);
                    Log.e("order", "onActivityResult: " + images);
                }
        }
    }

    private void showPhoto(Uri uri) {
        String path = uri.getPath();
        SPUtil.put(getContext(), "uri", path, "uri");
        Glide.with(this).load(new File(path)).into(ivFgChoosePicture);
        Log.e("camera", "onActivityResult: 这" + uri);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        // 注销订阅者
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        int code = event.getCode();
        if (code == 550) {
            // 更新界面
            CameraUtil.flushPciture(getContext(), event.getMessage());
            showPhoto(Uri.parse(event.getMessage()));
        }
    }

    public void rename(String string, final int id) {
        // layout = (LinearLayout) getLayoutInflater().inflate(R.layout.myedit,
        // null);
        LayoutInflater factory = LayoutInflater.from(getContext());
        View textEntryView = factory.inflate(R.layout.myedit, null);
        // removeView();
        //内部局部类，只能访问方法的final类型的变量
        final EditText mname_edit = (EditText) textEntryView
                .findViewById(R.id.rename_edit);
        if (id == R.id.tv_fg_phone) {
            mname_edit.setInputType(InputType.TYPE_CLASS_PHONE);
        }
        final TextView mname_text = textEntryView.findViewById(R.id.rename_message);
        mname_text.setText(string);
        // 不是用这个方法获取EditText的内容的
        // mname_edit.addTextChangedListener(mTextWatcher);

        // create a dialog
        new AlertDialog.Builder(getContext())
                //  .setIcon(R.drawable.icon)
                //  .setTitle(R.string.title_name)
                .setView(textEntryView)
                .setNegativeButton(R.string.cancle,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // TODO Auto-generated method stub
                            }
                        })
                .setPositiveButton(R.string.commit,
                        new DialogInterface.OnClickListener() {

                            private String newName;

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // dialog.
                                // TODO Auto-generated method stub
                                // Log.v(TAG, "你点击了确定");
                                if (!mname_edit.getText().toString().equals("")) {
                                    newName = mname_edit.getText().toString();
                                }
                                switch (id) {
                                    case R.id.tv_fg_name:
                                        orderName = newName;
                                        saveOrderInfo();
                                        tvFgName.setText(newName);
                                        break;
                                    case R.id.tv_fg_phone:
                                        orderPhone = newName;
                                        saveOrderInfo();
                                        tvFgPhone.setText(newName);
                                        break;
                                }
                                // newName = mname_edit.getText().toString();

                                //Log.v(TAG, "$$$$$btn.setText(newName);");
                            }

                        }).show();

    }

    private void saveOrderInfo() {

        // getUserAddress();
        if (orderName == null || orderName.equals("")) {

        } else if (orderAge == null || orderAge.equals("")) {

        } else if (orderSex == null || orderSex.equals("")) {

        } else if (orderPhone == null || orderPhone.equals("")) {

        } else {
            if (BlEUtile.isNetworkConnected(getContext())) {
                OkhttpUtils mOkhttpUtils = new OkhttpUtils(getActivity(), Contants.ORDER_INFO_CODE, new OkListener() {
                    @Override
                    public void onSuccess(int requestCode, String string) {
                        Log.e("====info===", "===397==" + string);
                    }

                    @Override
                    public void onError(int requestCode, IOException e) {
                        Log.e("====info===", "===402==" + e);
                    }
                });
                map.clear();
                map.put("usernick", orderName);
                map.put("age", orderAge);
                map.put("sex", orderSex);
                map.put("phone", orderPhone);
                map.put("uuid", mUniquePsuedoID);
                map.put("userge", city);
                Log.e("====info===", "===412==" + map);
                mOkhttpUtils.postForm(Contants.ORDER_INFO_CODE, Contants.BASE_URL + "ug.link", map);
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("orderName", orderName);
                jsonObject.put("orderAge", orderAge);
                jsonObject.put("orderSex", orderSex);
                jsonObject.put("orderPhone", orderPhone);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            isCommitInfo = true;
            SPUtil.put(getContext(), "isCommitInfo", isCommitInfo, "isCommitInfo");
            SPUtil.put(getContext(), "orderInfo", jsonObject, "orderInfo");
            Log.e("json", "saveOrderInfo: " + jsonObject);
        }
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(getActivity(), R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!getActivity().isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    @OnClick({R.id.iv_fg_choose_picture, R.id.tv_fg_choose_picture, R.id.ll_fg_name, R.id.ll_fg_age, R.id.ll_fg_sex, R.id.ll_fg_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_fg_choose_picture:
            case R.id.tv_fg_choose_picture:

                List<String> names = new ArrayList<>();
                names.add(getResources().getString(R.string.camera));
                names.add(getResources().getString(R.string.album));

                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0:
                                if (BlEUtile.checkCameraPermission(getContext())) {
                                    tempFile = cameraUtil.useFragmentCamera(OrderFragment.this, 0);
                                } else {

                                    new AlertDialog.Builder(getContext()).setTitle(R.string.permission_error_title)
                                            .setMessage(R.string.permission_error_message_location)
                                            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
                                                }
                                            })
                                            .show();
                                }
                                //   tempFile = cameraUtil.useCamera(getActivity(), 0);
                                break;
                            case 1:
                                //cameraUtil.useFragmentPicture(OrderFragment.this);

                                //单选
                                ImageSelector.builder()
                                        .useCamera(true) // 设置是否使用拍照
                                        .setSingle(true)  //设置是否单选
                                        .setViewImage(true) //是否点击放大图片查看,，默认为true
                                        .start(getActivity(), REQUEST_CODE); // 打开相册

                                break;
                        }
                    }
                }, names);

                //   cameraUtil.useCamera(getActivity(), 0);
//                cameraUtil.getCameraDialog(getActivity(),btnlistener,R.layout.layout_camera_test_water,1);
                break;
            case R.id.ll_fg_name:
                rename(getResources().getString(R.string.change_name), R.id.tv_fg_name);
                break;
            case R.id.ll_fg_age:
                requestChoose(ages, getResources().getString(R.string.change_age), R.id.tv_fg_age);
                break;
            case R.id.ll_fg_sex:
                requestChoose(sexs, getResources().getString(R.string.change_sex), R.id.tv_fg_sex);
                break;
            case R.id.ll_fg_phone:
                rename(getResources().getString(R.string.change_phone), R.id.tv_fg_phone);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (permissions[0].equals(Manifest.permission.CAMERA)) {
                tempFile = cameraUtil.useFragmentCamera(OrderFragment.this, 0);
            }
        }
    }

    private void requestChoose(String[] items, String textName, final int id) {
        SinglePicker<String> picker = new SinglePicker<>(getActivity(), items);
        picker.setCanLoop(false);//不禁用循环
        picker.setTopBackgroundColor(0xFFEEEEEE);
        picker.setTopHeight(50);
        picker.setTopLineColor(0xFF33B5E5);
        picker.setTopLineHeight(1);
        picker.setTitleText(textName);
        picker.setTitleTextColor(0xFF33B5E5);
        picker.setTitleTextSize(13);
        picker.setCancelTextColor(0xFF33B5E5);
        picker.setCancelTextSize(13);
        picker.setSubmitTextColor(0xFF33B5E5);
        picker.setSubmitTextSize(13);
        picker.setSelectedTextColor(0xFF33C5E5);
        picker.setUnSelectedTextColor(0xFF999999);
        picker.setWheelModeEnable(false);
        LineConfig config = new LineConfig();
        config.setColor(Color.BLUE);//线颜色
        config.setAlpha(120);//线透明度

        // config.setRatio(1);//线比率
        //  config.setThick(30);
        picker.setLineConfig(config);
        picker.setItemWidth(200);
        picker.setBackgroundColor(0xFFE1E1E1);
        //picker.setSelectedItem(isChinese ? "处女座" : "Virgo");
        switch (id) {
            case R.id.tv_fg_name:
                break;
            case R.id.tv_fg_age:
                picker.setSelectedIndex(16);
                break;
            case R.id.tv_fg_sex:
                picker.setSelectedIndex(0);
                break;
        }

        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                // showToast("index=" + index + ", item=" + item);
                //test.setText(item);
                switch (id) {
                    case R.id.tv_fg_age:
                        orderAge = item;
                        saveOrderInfo();
                        tvFgAge.setText(item);
                        break;
                    case R.id.tv_fg_sex:
                        orderSex = item;
                        saveOrderInfo();
                        tvFgSex.setText(item);
                        break;

                }
            }
        });
        picker.show();
    }
}
